package com.douyin.controller;

import com.douyin.common.Result;
// import com.douyin.service.DouyinHtmlParserService; // 已禁用
import com.douyin.service.DouyinParseService;
// import com.douyin.service.DouyinTokenService; // 已禁用
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 抖音解析测试控制器
 * 用于测试改进后的解析功能
 */
@Slf4j
@RestController
@RequestMapping("/api/test")
public class DouyinTestController {

    @Autowired
    private DouyinParseService parseService;

    // 注释掉已禁用的服务 - 改用第三方API
    // @Autowired
    // private DouyinHtmlParserService htmlParserService;
    // @Autowired
    // private DouyinTokenService tokenService;

    /**
     * 测试第三方API解析方法 (替换原HTML解析)
     */
    @PostMapping("/html-parse")
    public Result<Object> testThirdPartyApiParse(@RequestBody Map<String, String> request) {
        try {
            String shareText = request.get("shareText");
            if (shareText == null || shareText.trim().isEmpty()) {
                return Result.error("分享内容不能为空");
            }

            log.info("测试第三方API解析: {}", shareText);
            
            // 使用新的第三方API解析方法
            Map<String, Object> result = parseService.parseDouyinUrl(shareText);
            
            return Result.success(result);
            
        } catch (Exception e) {
            log.error("第三方API解析测试失败: {}", e.getMessage(), e);
            return Result.error("第三方API解析测试失败: " + e.getMessage());
        }
    }

    /**
     * 测试第三方API配置信息
     */
    @PostMapping("/token-generate")
    public Result<Object> testApiConfig(@RequestBody Map<String, String> request) {
        try {
            String shareText = request.get("shareText");
            if (shareText == null || shareText.trim().isEmpty()) {
                shareText = "测试分享文本";
            }

            log.info("测试第三方API配置: {}", shareText);
            
            Map<String, Object> result = new HashMap<>();
            
            // 显示第三方API配置信息
            result.put("apiUrl", "https://www.52api.cn/api/video_parse");
            result.put("apiDescription", "第三方抖音解析API");
            result.put("inputFormat", "分享文本或抖音链接");
            result.put("status", "第三方API模式已启用");
            result.put("browserPoolStatus", "已禁用");
            result.put("performanceNote", "第三方API解析速度更快，无需浏览器资源");
            
            return Result.success(result);
            
        } catch (Exception e) {
            log.error("API配置测试失败: {}", e.getMessage(), e);
            return Result.error("API配置测试失败: " + e.getMessage());
        }
    }

    /**
     * 第三方API性能测试
     */
    @PostMapping("/compare-parse")
    public Result<Object> testApiPerformance(@RequestBody Map<String, String> request) {
        try {
            String shareText = request.get("shareText");
            if (shareText == null || shareText.trim().isEmpty()) {
                return Result.error("分享内容不能为空");
            }

            log.info("第三方API性能测试: {}", shareText);
            
            Map<String, Object> result = new HashMap<>();
            
            // 测试第三方API方法
            long startTime = System.currentTimeMillis();
            Map<String, Object> apiResult = parseService.parseDouyinUrl(shareText);
            long apiTime = System.currentTimeMillis() - startTime;
            
            result.put("apiResult", apiResult);
            result.put("apiTime", apiTime + "ms");
            
            // 性能分析
            Map<String, Object> performance = new HashMap<>();
            performance.put("apiSuccess", Boolean.TRUE.equals(apiResult.get("success")));
            performance.put("parseMethod", apiResult.get("parseMethod"));
            performance.put("responseTime", apiTime + "ms");
            performance.put("performance", apiTime < 2000 ? "优秀" : apiTime < 5000 ? "良好" : "一般");
            
            result.put("performanceAnalysis", performance);
            
            // 与之前浏览器方式的对比
            Map<String, Object> comparison = new HashMap<>();
            comparison.put("browserMethodTime", "通常 9000ms+ (服务器环境)");
            comparison.put("apiMethodTime", apiTime + "ms");
            comparison.put("improvement", "性能提升约 " + Math.max(1, (9000 / Math.max(1, apiTime))) + " 倍");
            comparison.put("resourceUsage", "无需浏览器实例，内存占用大幅降低");
            
            result.put("comparison", comparison);
            
            return Result.success(result);
            
        } catch (Exception e) {
            log.error("性能测试失败: {}", e.getMessage(), e);
            return Result.error("性能测试失败: " + e.getMessage());
        }
    }

    /**
     * 测试URL清理和提取
     */
    @PostMapping("/test-url-extraction")
    public Result<Object> testUrlExtraction(@RequestBody Map<String, String> request) {
        try {
            String shareText = request.get("shareText");
            if (shareText == null || shareText.trim().isEmpty()) {
                return Result.error("分享内容不能为空");
            }

            log.info("测试URL提取: {}", shareText);
            
            Map<String, Object> result = new HashMap<>();
            
            // 使用内部方法测试URL提取（需要通过反射或创建测试方法）
            result.put("originalText", shareText);
            result.put("isValidDouyin", parseService.isValidDouyinUrl(shareText));
            
            return Result.success(result);
            
        } catch (Exception e) {
            log.error("URL提取测试失败: {}", e.getMessage(), e);
            return Result.error("URL提取测试失败: " + e.getMessage());
        }
    }

    /**
     * 获取测试用例
     */
    @GetMapping("/sample-data")
    public Result<Object> getSampleData() {
        Map<String, Object> sampleData = new HashMap<>();
        
        // 提供一些测试用例格式（不包含真实链接）
        sampleData.put("sampleShareText", "3.84 复制打开抖音，看看【拍照的徐老私的图文作品】光影是最好的滤镜。# 少女写真 # 我又心动了 #... https://v.douyin.com/44c7mkjv7ZE/ y@G.Vy RXM:/ 02/05");
        sampleData.put("description", "这些是测试用的示例数据，请替换为真实的抖音分享内容进行测试");
        
        // 第三方API配置信息
        Map<String, Object> apiInfo = new HashMap<>();
        apiInfo.put("apiUrl", "https://www.52api.cn/api/video_parse");
        apiInfo.put("apiKey", "YOK2Sm1FTUP8PTouS4haxJW0tA");
        apiInfo.put("method", "GET/POST");
        apiInfo.put("parameters", "key 和 url");
        apiInfo.put("urlExtraction", "自动从分享文本中提取 https://v.douyin.com/xxx/ 格式的链接");
        apiInfo.put("performance", "响应速度显著优于浏览器方式");
        
        sampleData.put("thirdPartyApiInfo", apiInfo);
        
        // 系统状态信息
        Map<String, Object> systemStatus = new HashMap<>();
        systemStatus.put("browserPoolStatus", "已禁用");
        systemStatus.put("seleniumStatus", "已禁用");
        systemStatus.put("thirdPartyApiStatus", "已启用");
        systemStatus.put("performanceMode", "高性能API模式");
        systemStatus.put("resourceUsage", "低内存占用，无需ChromeDriver");
        
        sampleData.put("systemStatus", systemStatus);
        
        return Result.success(sampleData);
    }

    /**
     * 健康检查
     */
    @GetMapping("/health")
    public Result<String> health() {
        return Result.success("第三方API解析模式运行正常 - 浏览器池已禁用");
    }
}